package com.yilin.tms.order.service.party.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yilin.commons.util.ArrayUtil;
import com.yilin.commons.util.DateTimeUtil;
import com.yilin.commons.util.StringUtil;
import com.yilin.tms.core.application.PageData;
import com.yilin.tms.core.commons.utils.ParamUtil;
import com.yilin.tms.core.commons.utils.QueryUtil;
import com.yilin.tms.core.entity.gps.gaode.GeoCalResult;
import com.yilin.tms.core.entity.order.party.OrderAppraise;
import com.yilin.tms.core.entity.order.transit.TransitOrder;
import com.yilin.tms.core.entity.user.account.Account;
import com.yilin.tms.core.entity.user.UserType;
import com.yilin.tms.core.entity.user.account.UserAccrual;
import com.yilin.tms.order.mapper.party.OrderAppraiseMapper;
import com.yilin.tms.order.mapper.transit.TransitOrderMapper;
import com.yilin.tms.order.service.party.IOrderAppraiseService;
import com.yilin.tms.order.service.party.IOrderAutLogService;
import com.yilin.tms.core.remote.IGpsRemote;
import com.yilin.tms.core.remote.IUserRemote;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 运单评价Service
 *
 * @author zhangjinyuan
 * @date 2022/10/29
 */
@Service
@Transactional
public class OrderAppraiseService extends ServiceImpl<OrderAppraiseMapper, OrderAppraise> implements IOrderAppraiseService {

    @Resource
    IOrderAutLogService orderAutLogService;
    @Resource
    TransitOrderMapper transitOrderMapper;
    @Resource
    IUserRemote userRemote;
    @Resource
    IGpsRemote gpsRemote;
    @Resource
    OrderAppraiseMapper orderAppraiseMapper;

    /**
     * 获取评价分页
     */
    @Override
    public PageData<OrderAppraise> getOrganizeAppraisePage(Account loginUser,String organizeId,  OrderAppraise query, Integer start, Integer limit) {
        QueryWrapper<OrderAppraise> queryWrapper = new QueryWrapper<>();
        if (organizeId != null) queryWrapper.eq("to_organize_id",organizeId);
//        if (loginUser.getUserType() == UserType.platformUser) queryWrapper.eq("plat_id",loginUser.getOrganizeId());
//        if (loginUser.getUserType() == UserType.zoneUser) queryWrapper.eq("zone_plat_id",loginUser.getOrganizeId());
        queryWrapper =  QueryUtil.andQueryWrapper(new QueryWrapper<>(),query);
        PageData<OrderAppraise> page = page(new PageData<>(start, limit),queryWrapper);
        for (OrderAppraise orderAppraise : page.getList()) {
            //隐藏评价敏感信息
            privateOrderAppraiseData(loginUser, orderAppraise);
        }
        return page;
    }

    @Override
    public List<OrderAppraise> getTopTenAppraiseList(String organizeId) {
        QueryWrapper<OrderAppraise> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("to_organize_id",organizeId);
        PageData<OrderAppraise> pageData = new PageData<>(1, 10);
        PageData<OrderAppraise> page = orderAppraiseMapper.selectPage(pageData, queryWrapper);
        return page.getList();
    }

    //批量修改评价状态
    @Override
    public void updateAuditStateList(String[] appraiseIds, OrderAppraise.AuditState auditState) {
        List<OrderAppraise>  orderAppraiseList=orderAppraiseMapper.selectBatchIds(Arrays.asList(appraiseIds));
        ParamUtil.isNull(orderAppraiseList,"获取评价订单失败");
        for (int i = 0; i <orderAppraiseList.size() ; i++) {
            orderAppraiseList.get(i).setAuditState(auditState);
        }
        saveOrUpdateBatch(orderAppraiseList);
    }
    /**
     * 保存运单评价
     * 评价直接影响信用评级
     */
    @Override
    public void saveOrderAppraise(Account loginUser, OrderAppraise orderAppraise, TransitOrder transitOrder) {
        orderAppraise.setAuditState(OrderAppraise.AuditState.waiting);
        orderAppraise.setTransitOrderId(transitOrder.getId());
        orderAppraise.setTransportNo(transitOrder.getTransportNo());

        orderAppraise.setFromAccountId(loginUser.getId());
        orderAppraise.setFromAccountName(loginUser.getName());
        orderAppraise.setFromOrganizeId(loginUser.getOrganizeId());
        orderAppraise.setFromOrganizeName(loginUser.getOrganizeName());
        orderAppraise.setFromOrganizeLogo(loginUser.getOrganizeLogo());

        orderAppraise.setToAccountId(transitOrder.getTransitTruckUserId());
        orderAppraise.setToAccountName(transitOrder.getTransitTruckUserName());
        orderAppraise.setToOrganizeId(transitOrder.getRobOrganizeId());
        orderAppraise.setToOrganizeName(transitOrder.getRobOrganizeName());
        orderAppraise.setToOrganizeLogo(transitOrder.getRobOrganizeLogo());
        orderAppraise.setToTruckerName(transitOrder.getTransitTruckUserName());
        orderAppraise.setToTruckNo(transitOrder.getTransitTruckNo());

        orderAppraise.setGoodsOrderId(transitOrder.getGoodsOrderId());
        orderAppraise.setTitle(transitOrder.getTitle());
        orderAppraise.setGoodsOrderType(transitOrder.getGoodsOrderType());
        orderAppraise.setGoodsOrderNo(transitOrder.getGoodsOrderNo());
        orderAppraise.setFullLoad(transitOrder.getFullLoad());

        orderAppraise.setAddUserId(loginUser.getId());
        orderAppraise.setCreateTime(new Date());
        //计算运单距离
//        GeoCalResult success = ParamUtil.isSuccess(gpsRemote.getDrivingCalculation(transitOrder.getPlatId(),
//                transitOrder.getPlanningConsignorCoordinate(), transitOrder.getPlanningConsigneeCoordinate()));
//        orderAppraise.setKilometer(success.getDistance()/1000d);
        //计算运单时间
        orderAppraise.setDuration(DateTimeUtil.secondBetween(transitOrder.getStartTransitTime(), transitOrder.getReceiptTime()));
        saveOrUpdate(orderAppraise);
        //更新运单信息
        transitOrder.setUpdateTime(new Date());
        transitOrder.setUpdateUserId(loginUser.getId());
        transitOrder.setAlreadyAppraise(true);
        transitOrderMapper.updateById(transitOrder);
        //更新被评价人信息
        UserAccrual userAccrual = UserAccrual.appraiseAccrual(orderAppraise.getAppraiseGrade());
        ParamUtil.isSuccess(userRemote.updateUserAccrual(orderAppraise.getToAccountId(), userAccrual));
        //保存操作记录
        String format = String.format("%s对运单发起评价,评分:%s,内容:%s", orderAppraise.getFromAccountName(),
                orderAppraise.getAppraiseGrade(), orderAppraise.getAppraiseText());
        orderAutLogService.saveTransitAutLog(orderAppraise.getTransitOrderId(), loginUser, "【发起评价】", format);
    }

    /**
     * 定时任务 自动评价
     */
    @Override
    public void autoOrderAppraise() {
        QueryWrapper<TransitOrder> queryWrapper = new QueryWrapper<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE,-7);
        queryWrapper.lt("receipt_time",calendar.getTime());
        List<TransitOrder> list = transitOrderMapper.selectList(queryWrapper);
        if (ArrayUtil.isEmpty(list)) return;
        list.forEach(transitOrder -> {
            OrderAppraise orderAppraise = getOne(new QueryWrapper<OrderAppraise>()
                    .eq("transit_order_id", transitOrder.getId()));
            if (orderAppraise == null) {
                OrderAppraise appraise = new OrderAppraise();
                appraise.setAppraiseGrade(4D);
                appraise.setAppraiseText("此用户没有填写评价");
                Account account = ParamUtil.isSuccess(userRemote.getAccountById(transitOrder.getShipperAccountId()));
                saveOrderAppraise(account, appraise, transitOrder);
            }
        });
    }

    /**
     * 内部 隐藏评价敏感信息
     */
    private void privateOrderAppraiseData(Account loginUser, OrderAppraise orderAppraise) {
        if (loginUser.getUserType() != UserType.platformUser &&
                !loginUser.getId().equals(orderAppraise.getFromAccountId()) &&
                !loginUser.getId().equals(orderAppraise.getToAccountId())) {
            //隐藏敏感信息
            orderAppraise.setFromAccountName(StringUtil.privateName(orderAppraise.getFromAccountName()));
            orderAppraise.setFromOrganizeName(StringUtil.privateName(orderAppraise.getFromOrganizeName()));
            orderAppraise.setToAccountName(StringUtil.privateName(orderAppraise.getFromAccountName()));
            orderAppraise.setToOrganizeName(StringUtil.privateName(orderAppraise.getFromOrganizeName()));
        }
    }
}
